package com.example.lib5.search;

import java.util.Arrays;

public class FibonacciSearch {
    static int maxSize = 20;

    public static void main(String[] args) {
        int[] arr = {1, 8, 10, 89, 1000, 1234};
        int i = fibSearch(arr, 89);
        System.out.println(i);
    }

    //斐波那契队列
    public static int[] fib() {
        int[] f = new int[maxSize];
        f[0] = 1;
        f[1] = 1;
        for (int i = 2; i < maxSize; i++) {
            f[i] = f[i - 1] + f[i - 2];
        }
        System.out.println("斐波那契数列：" + Arrays.toString(f));
        return f;
    }

    public static int fibSearch(int[] a, int key) {
        int low = 0;
        int high = a.length - 1;
        int k = 0;
        int mid = 0;
        int f[] = fib();
        /**
         * 获取斐波那契那几
         * 数列最右边位置与斐波那契队列比较获取k
         * todo -1?
         */
        while (high > f[k] - 1) {
            k++;
        }
        /**
         * f[k]=8
         * 长度补充到8,后补0
         */
        int[] temp = Arrays.copyOf(a, f[k]);//[1, 8, 10, 89, 1000, 1234, 0, 0]
        System.out.println(Arrays.toString(temp));
        for (int i = high + 1; i < temp.length; i++) {
            temp[i] = a[high];
        }//[1, 8, 10, 89, 1000, 1234, 1234, 1234]
        System.out.println(Arrays.toString(temp));
        while (low <= high) {
            /**
             * 中间值
             *
             */
            mid = low + f[k - 1] - 1;
            if (key <= temp[mid]) {
                high = mid - 1;
                k--;
            } else if (key > temp[mid]) {
                low = mid + 1;
                k -= 2;
            } else {
                if (mid <= high) {
                    return mid;
                } else {
                    return high;
                }
            }
        }
        return -1;
    }
}
